<template>
    <a-upload
        v-model:file-list="fileList"
        :action="OSSData.host"
        :list-type="listType"
        :data="getExtraData"
        :beforeUpload="beforeUpload"
        :headers="{
            authorization: 'authorization-text'
        }"
        @change="handleChange"
    >
        <slot></slot>
    </a-upload>
</template>
<script>
export default {
    name: 'OssUpload'
}
</script>
<script setup>
import { ref, getCurrentInstance, onMounted, defineProps, defineEmits } from 'vue'
import { getOssConfigAPI } from '@/api/common.js'
const { proxy: _this } = getCurrentInstance()
const props = defineProps({
    listType: {
        type: String,
        default: 'picture'
    },
    maxCount: {
        type: Number,
        default: 1
    }
})
const emit = defineEmits(['update:value'])
const fileList = ref([])
const OSSData = ref({})
//获取oss配置项
const getOssConfig = async () => {
    const res = await getOssConfigAPI()
    OSSData.value = res
}
//上传前的处理
const beforeUpload = async (file) => {
    const expire = OSSData.value.expire * 1000
    if (expire < Date.now()) {
        getOssConfig()
    }
    const dir = 'react/'
    const suffix = file.name.slice(file.name.lastIndexOf('.'))
    const filename = Date.now() + suffix
    file.key = OSSData.value.dir + dir + Date.now() + suffix
    file.url = OSSData.value.host + OSSData.value.dir + dir + filename
    console.log(file, '111')
    return file
}
//向父组件抛出需要的key
const handleChange = ({ file }) => {
    //上传完成  抛出key
    if (file.status === 'done') {
        emit('update:value', file.key)
    }
    //移除之后 key变为空
    if (file.status === 'removed') {
        emit('update:value', '')
    }
}
//配置项
const getExtraData = (file) => {
    return {
        key: file.key,
        OSSAccessKeyId: OSSData.value.accessid,
        policy: OSSData.value.policy,
        Signature: OSSData.value.signature
    }
}

onMounted(() => {
    getOssConfig()
})
</script>
<style scoped lang="scss"></style>
